﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace QuickBencher.Repositories
{
    public class MeasurementRepository
    {
        private static string quickBencherDir =
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "QuickBencher");
        private static string measurementsDataFile = Path.Combine(quickBencherDir, "measurements.quickbencher");

        public virtual void Save(Measurement measurement)
        {
			if (!IsInfrastructureForPersistanceUp())
	           SetupInfrastructureForPersistance();

        	var data = GetPersistetData();
			data.Add(new MeasurementDTO()
			         {
			         	Label = measurement.Label,
						RealTime = measurement.RealTime,
						SystemTime = measurement.SystemTime,
						TotalTime = measurement.TotalTime,
						UserTime = measurement.UserTime
			         });
			Persist(data);
        }

		private static bool IsInfrastructureForPersistanceUp()
		{
			return IsQuickBencherDirCreated() && IsQuickBencherDataFileCreated();
		}

    	private static bool IsQuickBencherDirCreated()
    	{
    		return Directory.Exists(quickBencherDir);
    	}

    	private static void CreateQuickBencherDir()
    	{
    		Directory.CreateDirectory(quickBencherDir);
    	}

    	private static void SetupInfrastructureForPersistance()
    	{
			CreateQuickBencherDir();
			CreateQuickBencherDataFile();
    	}

    	private static bool IsQuickBencherDataFileCreated()
    	{
    		return File.Exists(measurementsDataFile);
    	}

    	private static void CreateQuickBencherDataFile()
    	{
    		Persist(new List<MeasurementDTO>());
    	}

    	private static void Persist(List<MeasurementDTO> obj)
    	{
    		using (var sw = new StreamWriter(measurementsDataFile))
    		{
    			sw.Write(JsonConvert.SerializeObject(obj, Formatting.Indented));
    		}
    	}

		private static List<MeasurementDTO> GetPersistetData()
		{
			using (var sr = new StreamReader(measurementsDataFile))
			{
				return JsonConvert.DeserializeObject<List<MeasurementDTO>>(sr.ReadToEnd());
			}
		}

    	public IEnumerable<Measurement> GetAll()
        {
    		var data = from measurement in GetPersistetData()
    		           select new Measurement()
    		                  {
    		                  	Label = measurement.Label,
    		                  	RealTime = measurement.RealTime,
    		                  	SystemTime = measurement.SystemTime,
    		                  	TotalTime = measurement.TotalTime,
    		                  	UserTime = measurement.UserTime
    		                  };
    		return data;
        }
    }
}
